import Local from "./communication-strategy/local.js";
import Remote from "./communication-strategy/remote.js";
import { defaultOptions } from "./constant.js";
import Rtc from "./communication-strategy/webrtc.js";

/**
 * 判断选择合适的通信策略
 */
function judge(id, options) {
  options = { ...defaultOptions, ...options };

  return new Promise((resolve) => {
    // 竟选最优的策略方案
    const local = new Local(id, options);
    local.check(resolve);
    const remote = new Remote(id, {
      ...options,
      onConnect() {
        // 如果resolve已经执行，则不进行远程检测了。
        if (resolve.isExecute) {
          remote.destroy();
          return;
        }
        remote.check(resolve);
      },
    });

    // const rtc = new Rtc(id, {
    //   ...options,
    //   onConnect() {
    //     if (resolve.isExecute) {
    //       rtc.destroy();
    //       return;
    //     }
    //     rtc.check(resolve);
    //   },
    // });
  });
}

class Communication {
  client = null;
  localClient = null;
  remoteClient = null;
  init(id, options) {
    this.options = options;
    this.id = id;
    options = { ...defaultOptions, ...this.options };
    return new Promise((resolve) => {
      // 竟选最优的策略方案
      // this.localClient = new Local(this.id, options);
      // this.localClient.check(resolve);
      this.remoteClient = new Remote(this.id, {
        ...options,
        onConnect: () => {
          // 如果resolve已经执行，则不进行远程检测了。
          // if (resolve.isExecute) {
          //   this.remoteClient.destroy();
          //   return;
          // }
          console.log("执行 onConnect");
          this.remoteClient.check(resolve);

          // this.localClient.destroy();
        },
      });
    });
  }

  destroy() {
    this.remoteClient?.destroy();
  }
}

export default new Communication();
